﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestLogMonitor.Common;

namespace TestLogMonitor.ViewModel
{
    public class SelectProductViewModel:ViewModelBase
    {
        #region 属性
        private string actor;
        /// <summary>
        /// 工号
        /// </summary>
        public string Actor
        {
            get { return actor; }
            set { actor = value; this.RaisePropertyChanged(() => Actor); }
        }
        private ObservableCollection<string> pns;
        /// <summary>
        /// 产品信息
        /// </summary>
        public ObservableCollection<string> PNs
        {
            get { return pns; }
            set { pns = value; this.RaisePropertyChanged(() => PNs); }
        }

        #endregion

        #region 命令
        private RelayCommand loadPageCmd;

        public RelayCommand LoadPageCmd
        {
            get
            {
                loadPageCmd = loadPageCmd ?? new RelayCommand(LoadedPage);
                return loadPageCmd;
            }
            set { loadPageCmd = value; }
        }
        private RelayCommand<string> lstPNMouseDoubleClick;

        public RelayCommand<string> LstPNMouseDoubleClick
        {
            get
            {
                lstPNMouseDoubleClick = lstPNMouseDoubleClick ?? new RelayCommand<string>(LstPNMouseDoubleClickHandler);
                return lstPNMouseDoubleClick;
            }
            set { lstPNMouseDoubleClick = value; }
        }

        #endregion

        #region 方法
        //页面加载
        private void LoadedPage()
        {
            _ = AddPNsToListAsync();

        }
        //添加机种信息到列表中
        private async Task AddPNsToListAsync()
        {
            await Task.Run(() => {
                PNs = new ObservableCollection<string>();
                string directoryPN = Path.Combine(Environment.CurrentDirectory, "Product");
                var productConfigFiles= Directory.GetFiles(directoryPN,"*.cfg");
                string product = string.Empty;
                foreach (var pf in productConfigFiles)
                {
                    product = Path.GetFileNameWithoutExtension(pf);
                    if (!PNs.Contains(product))
                    {
                        PNs.Add(product);
                    }
                }
            });
        }
        //机种列表的双击事件
        private void LstPNMouseDoubleClickHandler(string obj)
        {
            if (obj != null)
            {
                GlobalInfo.Actor = this.Actor;
                ViewManager.Close("SelectProduct");
                Messenger.Default.Send<string>(obj, "PartNumber");
            }
        }

        #endregion
    }
}
